﻿using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using OpenAI;
using System;
using System.ClientModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace llmChat
{
    public class ai_Chat
    {
        async static Task Chat(string[] args)
        {
            try
            {
                await Test();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"程序出错: {ex.Message}");
            }
        }

        // 资源管理改进方案
        static async Task Test()
        {
            // 获取配置
            var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
            ChatModel chatParam = config.GetSection("aliyun").Get<ChatModel>();

            // 使用using确保资源释放
            var credential = new ApiKeyCredential(chatParam.APIKey);
            var options = new OpenAIClientOptions { Endpoint = new Uri(chatParam.BaseUrl) };
            var client = new OpenAIClient(credential, options);
            using var chatClient = client.GetChatClient(chatParam.ModelName).AsIChatClient();

            List<ChatMessage> chatHistory = new();
            chatHistory.Add(new ChatMessage(ChatRole.System, "你是一个智能助手"));

            // 添加CancellationToken支持
            using var cts = new CancellationTokenSource();
            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                cts.Cancel();
            };

            while (!cts.IsCancellationRequested)
            {
                Console.Write("Your(exit退出对话)：");
                var msg = Console.ReadLine()?.Trim(); // 处理null和空字符串
                if (msg == "exit") break;

                chatHistory.Add(new ChatMessage(ChatRole.User, msg));

                try
                {
                    Console.WriteLine("AI Response:");
                    string response = "";
                    await foreach (var item in chatClient.GetStreamingResponseAsync(
                        chatHistory,
                        cancellationToken: cts.Token))
                    {
                        Console.Write(item.Text);
                        response += item.Text;
                    }
                    chatHistory.Add(new ChatMessage(ChatRole.Assistant, response));
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("\n操作已取消");
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"\n请求出错: {ex.Message}");
                }
            }
        }
    }
}
